package com.example.service;

import com.example.entity.Coupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.json.JSONObject;
import org.json.JSONArray;

import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class DatabaseCommandParser {

    @Autowired
    private CouponService couponService;
    
    // 解析用户的数据库操作请求
    public String parseAndExecuteCommand(String userInput) {
        String input = userInput.toLowerCase().trim();
        
        try {
            // 查询操作
            if (input.contains("查询") || input.contains("查看") || input.contains("显示") || input.contains("获取")) {
                return handleQueryCommand(input, userInput);
            }
            // 添加操作
            else if (input.contains("添加") || input.contains("创建") || input.contains("新增")) {
                return handleCreateCommand(input, userInput);
            }
            // 更新操作
            else if (input.contains("更新") || input.contains("修改") || input.contains("改变")) {
                return handleUpdateCommand(input, userInput);
            }
            // 删除操作
            else if (input.contains("删除") || input.contains("移除")) {
                return handleDeleteCommand(input, userInput);
            }
            // 统计操作
            else if (input.contains("统计") || input.contains("计数") || input.contains("数量")) {
                return handleCountCommand(input);
            }
            else {
                return "抱歉，我无法理解您的数据库操作请求。请使用类似'查询所有优惠券'、'添加优惠券'、'删除优惠券'等指令。";
            }
        } catch (Exception e) {
            return "执行数据库操作时发生错误：" + e.getMessage();
        }
    }
    
    // 处理查询命令
    private String handleQueryCommand(String input, String originalInput) {
        if (input.contains("所有") || input.contains("全部")) {
            List<Coupon> coupons = couponService.getAllCoupons();
            return formatCouponList("所有优惠券", coupons);
        }
        else if (input.contains("有效") || input.contains("启用")) {
            List<Coupon> coupons = couponService.getActiveCoupons();
            return formatCouponList("有效优惠券", coupons);
        }
        else if (input.contains("无效") || input.contains("禁用")) {
            List<Coupon> coupons = couponService.getCouponsByStatus(0);
            return formatCouponList("无效优惠券", coupons);
        }
        else {
            // 尝试提取优惠券名称或ID
            Pattern namePattern = Pattern.compile("查询.*?([\\u4e00-\\u9fa5a-zA-Z0-9]+).*?优惠券");
            Matcher nameMatcher = namePattern.matcher(originalInput);
            if (nameMatcher.find()) {
                String name = nameMatcher.group(1);
                List<Coupon> coupons = couponService.searchCouponsByName(name);
                return formatCouponList("包含'" + name + "'的优惠券", coupons);
            }
            
            Pattern idPattern = Pattern.compile("id.*?(\\d+)");
            Matcher idMatcher = idPattern.matcher(input);
            if (idMatcher.find()) {
                Long id = Long.parseLong(idMatcher.group(1));
                Optional<Coupon> coupon = couponService.getCouponById(id);
                if (coupon.isPresent()) {
                    return formatSingleCoupon(coupon.get());
                } else {
                    return "未找到ID为" + id + "的优惠券。";
                }
            }
            
            List<Coupon> coupons = couponService.getAllCoupons();
            return formatCouponList("所有优惠券", coupons);
        }
    }
    
    // 处理创建命令
    private String handleCreateCommand(String input, String originalInput) {
        // 提取优惠券名称
        Pattern namePattern = Pattern.compile("添加.*?([\\u4e00-\\u9fa5a-zA-Z0-9\\s]+).*?优惠券");
        Matcher nameMatcher = namePattern.matcher(originalInput);
        
        String couponName = "新优惠券";
        if (nameMatcher.find()) {
            couponName = nameMatcher.group(1).trim();
        }
        
        // 默认状态为有效
        Integer status = 1;
        if (input.contains("无效") || input.contains("禁用")) {
            status = 0;
        }
        
        Coupon newCoupon = couponService.createCoupon(couponName, status);
        return "成功创建优惠券：\n" + formatSingleCoupon(newCoupon);
    }
    
    // 处理更新命令
    private String handleUpdateCommand(String input, String originalInput) {
        Pattern idPattern = Pattern.compile("id.*?(\\d+)");
        Matcher idMatcher = idPattern.matcher(input);
        
        if (!idMatcher.find()) {
            return "请指定要更新的优惠券ID，例如：'更新ID为1的优惠券名称为新名称'";
        }
        
        Long id = Long.parseLong(idMatcher.group(1));
        
        // 提取新名称
        Pattern namePattern = Pattern.compile("名称.*?([\\u4e00-\\u9fa5a-zA-Z0-9\\s]+)");
        Matcher nameMatcher = namePattern.matcher(originalInput);
        String newName = null;
        if (nameMatcher.find()) {
            newName = nameMatcher.group(1).trim();
        }
        
        // 提取新状态
        Integer newStatus = null;
        if (input.contains("启用") || input.contains("有效")) {
            newStatus = 1;
        } else if (input.contains("禁用") || input.contains("无效")) {
            newStatus = 0;
        }
        
        Coupon updatedCoupon = couponService.updateCoupon(id, newName, newStatus);
        if (updatedCoupon != null) {
            return "成功更新优惠券：\n" + formatSingleCoupon(updatedCoupon);
        } else {
            return "未找到ID为" + id + "的优惠券。";
        }
    }
    
    // 处理删除命令
    private String handleDeleteCommand(String input, String originalInput) {
        Pattern idPattern = Pattern.compile("id.*?(\\d+)");
        Matcher idMatcher = idPattern.matcher(input);
        
        if (!idMatcher.find()) {
            return "请指定要删除的优惠券ID，例如：'删除ID为1的优惠券'";
        }
        
        Long id = Long.parseLong(idMatcher.group(1));
        boolean deleted = couponService.deleteCoupon(id);
        
        if (deleted) {
            return "成功删除ID为" + id + "的优惠券。";
        } else {
            return "未找到ID为" + id + "的优惠券。";
        }
    }
    
    // 处理统计命令
    private String handleCountCommand(String input) {
        if (input.contains("有效") || input.contains("启用")) {
            long count = couponService.countCouponsByStatus(1);
            return "有效优惠券数量：" + count + "个";
        } else if (input.contains("无效") || input.contains("禁用")) {
            long count = couponService.countCouponsByStatus(0);
            return "无效优惠券数量：" + count + "个";
        } else {
            long count = couponService.countCoupons();
            return "优惠券总数量：" + count + "个";
        }
    }
    
    // 格式化优惠券列表
    private String formatCouponList(String title, List<Coupon> coupons) {
        if (coupons.isEmpty()) {
            return title + "：暂无数据";
        }
        
        StringBuilder sb = new StringBuilder();
        sb.append(title).append("（共").append(coupons.size()).append("条）：\n\n");
        
        for (Coupon coupon : coupons) {
            sb.append("ID: ").append(coupon.getCouponId())
              .append(" | 名称: ").append(coupon.getCouponName())
              .append(" | 状态: ").append(coupon.getCouponStatus() == 1 ? "有效" : "无效")
              .append("\n");
        }
        
        return sb.toString();
    }
    
    // 格式化单个优惠券
    private String formatSingleCoupon(Coupon coupon) {
        return "ID: " + coupon.getCouponId() + 
               " | 名称: " + coupon.getCouponName() + 
               " | 状态: " + (coupon.getCouponStatus() == 1 ? "有效" : "无效");
    }
}
